﻿using Leeder.Logger;
using LeederGlobal;
using LeederWinApp;
using LeederWinApp.Business;
using LeederWinApp.Model;
using SPSAndong.Model;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace MainFrm.Forms
{
    public partial class FrmMain : Form
    {
        Dictionary<string, int> DicUIPages = new Dictionary<string, int>();
        public LogOperate LogObj => Log.GetLogger(this.GetType());
        MenuBLL menuBLL = new MenuBLL();

        SetupBLL setupBLL = new SetupBLL();
        UserBLL userBLL = new UserBLL();

        SetupModel AppSetupModel;
        UserModel DefaultUser;

        public FrmMain()
        {
            InitializeComponent();
        }

        private void uiNavMenu1_MenuItemClick(TreeNode node,NavMenuItem item, int pageIndex)
        {
            DicUIPages.TryGetValue(node.Text,out int index);
            MainContainer.SelectedIndex = index;
        }

        private void FrmMain_Load(object sender, EventArgs e)
        {
            //检查是否多开
            string processName = Process.GetCurrentProcess().ProcessName;
            Process[] processes = Process.GetProcessesByName(processName);
            //如果该数组长度大于1，说明多次运行
            if (processes.Length > 1)
            {
                UIMessageBox.ShowError("程序已运行，不能再次打开！");
                Environment.Exit(1);
            }

            Init_Control();

            AppSetupModel = setupBLL.GetModel();
            SystemConfigurationModel systemConfiguration = new SystemConfigurationModel();
            systemConfiguration.AppName = AppSetupModel.AppName;
            ApplicationCache.SystemConfiguration = systemConfiguration;
            labelSystemName.Text = ApplicationCache.ProductName;
            //打开软件加载默认用户
            DefaultUser = userBLL.GetById(AppSetupModel.DefaultAccountID).ActivedObj;

            if (AppSetupModel.IsAutoLogin)
            {
                ApplicationCache.CurrentUser = new CurrentUserModel { LoginName = DefaultUser.LoginName, Password = DefaultUser.Password, DisplayName = DefaultUser.DisplayName, Permission = DefaultUser.Permission };
            }
            else
            {
                //登录方法
                FLogin frm = new FLogin();
                frm.ShowDialog();
                if (frm.IsLogin)
                {
                    ApplicationCache.CurrentUser = new CurrentUserModel { LoginName = frm.user.LoginName, Password = frm.user.Password, DisplayName = frm.user.DisplayName, Permission = frm.user.Permission };
                    UIMessageTip.ShowOk("登录成功");
                    frm.Dispose();
                }
                else
                {
                    frm.Dispose();
                    Environment.Exit(0);
                }
            }

            var list = menuBLL.GetModelAll();

            Menu_Load(list);

            if (this.WindowState != FormWindowState.Maximized)
            {
                //全屏
                this.WindowState = FormWindowState.Maximized;
            }

            if (ApplicationCache.CurrentUser.Permission <= 1)
            {
                labelUser.Text = "管理员(" + ApplicationCache.CurrentUser.DisplayName + ")";
                if (AppSetupModel.ResetTime > 0)
                {
                    timer1.Start();
                }
            }
            else if (ApplicationCache.CurrentUser.Permission > 1)
            {
                labelUser.Text = "普通用户(" + ApplicationCache.CurrentUser.DisplayName + ")";
                if (AppSetupModel.ResetTime > 0 && AppSetupModel.IsReplacePage)
                {
                    timer1.Start();
                }
            }
        }

        private void Init_Control()
        {
            labelSystemName.ForeColor = Color.White;
            labelUser.ForeColor = Color.White;

            Aside.FillColor = Color.White;
            Aside.ForeColor = Color.DimGray;
            Aside.HoverColor = Color.WhiteSmoke;
            Aside.BackColor = Color.White;
            Aside.SelectedColor = Color.LightGray;
            //Aside.SecondBackColor = Color.DarkRed;

        }

        private void Menu_Load(List<MenuModel> menus)
        {
            var menus1 = menus.Where(t => t.MenuTier == 1).OrderBy(t => t.Sn).ToList();
            string strs = "";
            int pageIndex = -1;
            foreach (var menu in menus1)
            {

                //调用类库初始化方法,已经初始化则跳过
                if (!strs.Contains(menu.AssemblyName))
                {
                    string strClass = menu.AssemblyName + ".AppInitializer";
                    string strMethod = "Init";
                    try
                    {
                        Object obj = Assembly.Load(menu.AssemblyName).CreateInstance(strClass);   // 获取初始化类的实例
                        Type type = typen(strClass);       // 获取初始化类
                        MethodInfo method = type.GetMethod(strMethod, new Type[] { });      // 获取初始化方法信息
                        object[] parameters = null;                                // 初始化方法参数（空）
                        method.Invoke(obj, parameters);                           // 调用方法，参数
                        strs += menu.AssemblyName;                           //记录已初始化的类库，避免重复初始化
                    }
                    catch (Exception ex)
                    {

                    }
                }

                TreeNode treeNode = new TreeNode();
                treeNode.Text = menu.MenuName;

                var menus2 = menus.Where(t => t.ParentID == menu.ID).OrderBy(t => t.Sn).ToList();
                if (menus2 == null || menus2.Count <= 0)
                {
                    Object frmShow = Assembly.Load(menu.AssemblyName).CreateInstance(menu.ClassName);
                    AddPage((UIPage)frmShow);
                    pageIndex++;
                    DicUIPages.Add(menu.MenuName, pageIndex);
                }
                else
                {
                    foreach (var menu2 in menus2)
                    {
                        TreeNode node = new TreeNode();
                        node.Text = menu2.MenuName;
                        treeNode.Nodes.Add(node);
                        Object frmShow = Assembly.Load(menu2.AssemblyName).CreateInstance(menu2.ClassName);
                        AddPage((UIPage)frmShow);
                        pageIndex++;
                        DicUIPages.Add(menu2.MenuName, pageIndex);
                    }
                }
                Aside.Nodes.Add(treeNode);
            }
        }

        #region 捕捉电脑空闲时间
        [StructLayout(LayoutKind.Sequential)]
        struct LASTINPUTINFO
        {
            //设置结构体块容量
            [MarshalAs(UnmanagedType.U4)]
            public int cbSize;

            //捕获的时间
            [MarshalAs(UnmanagedType.U4)]
            public uint dwTime;
        }

        [DllImport("user32.dll")]
        private static extern bool GetLastInputInfo(ref LASTINPUTINFO plii);
        /// <summary>
        /// 捕捉电脑没有操作时间（毫秒）
        /// </summary>
        /// <returns></returns>
        private static long GetLastInputTime()
        {
            LASTINPUTINFO vLastInputInfo = new LASTINPUTINFO();
            vLastInputInfo.cbSize = Marshal.SizeOf(vLastInputInfo);
            //捕获时间
            if (!GetLastInputInfo(ref vLastInputInfo)) return 0;
            return Environment.TickCount - (long)vLastInputInfo.dwTime;
        }
        #endregion

        /// <summary>
        /// 根据设定时间内无操作自动降低用户权限
        /// </summary>
        private void InitPermission()
        {
            try
            {
                if (GetLastInputTime() > AppSetupModel.ResetTime * 1000)
                {
                    this.Invoke(new MethodInvoker(() =>
                    {
                        ApplicationCache.CurrentUser.Permission = DefaultUser.Permission;
                        ApplicationCache.CurrentUser.LoginName = DefaultUser.LoginName;
                        ApplicationCache.CurrentUser.Password = DefaultUser.Password;
                        ApplicationCache.CurrentUser.DisplayName = DefaultUser.DisplayName;
                        if (ApplicationCache.CurrentUser.Permission == -1)
                            labelUser.Text = "超级管理员(" + ApplicationCache.CurrentUser.DisplayName + ")";
                        else if (ApplicationCache.CurrentUser.Permission >= 0 && ApplicationCache.CurrentUser.Permission <= 1)
                            labelUser.Text = "管理员(" + ApplicationCache.CurrentUser.DisplayName + ")";
                        else if (ApplicationCache.CurrentUser.Permission > 1)
                        {
                            labelUser.Text = "普通用户(" + ApplicationCache.CurrentUser.DisplayName + ")";
                            if (AppSetupModel.IsReplacePage)
                            {
                                Aside.Width = 0;
                                Aside.SelectPage(AppSetupModel.ReplacePageNo);
                            }
                        }
                        timer1.Stop();
                    }));
                }
            }
            catch (Exception ex)
            {
                LogObj.Error(ex.Message);
            }
        }

        public UIPage AddPage(UIPage page)
        {
            //page.Frame = this;
            MainContainer.AddPage(page);
            return page;
        }

        /// <summary>
        /// 通过类名获取类型
        /// </summary>
        /// <param name="typeName">类名</param>
        /// <returns></returns>
        private Type typen(string typeName)
        {
            Type type = null;
            Assembly[] assemblyArray = AppDomain.CurrentDomain.GetAssemblies();
            int assemblyArrayLength = assemblyArray.Length;
            for (int i = 0; i < assemblyArrayLength; ++i)
            {
                type = assemblyArray[i].GetType(typeName);
                if (type != null)
                {
                    return type;
                }
            }

            for (int i = 0; (i < assemblyArrayLength); ++i)
            {
                Type[] typeArray = assemblyArray[i].GetTypes();
                int typeArrayLength = typeArray.Length;
                for (int j = 0; j < typeArrayLength; ++j)
                {
                    if (typeArray[j].Name.Equals(typeName))
                    {
                        return typeArray[j];
                    }
                }
            }
            return type;
        }

        #region 登录按钮方法
        private void uiAvatar1_MouseDown(object sender, MouseEventArgs e)
        {
            uiAvatar1.ForeColor = Color.FromArgb(80, 140, 255);
        }

        private void uiAvatar1_MouseHover(object sender, EventArgs e)
        {
            uiAvatar1.FillColor = Color.LightSteelBlue;
        }

        private void uiAvatar1_MouseLeave(object sender, EventArgs e)
        {
            uiAvatar1.FillColor = Color.Silver;
        }

        private void uiAvatar1_MouseUp(object sender, MouseEventArgs e)
        {
            uiAvatar1.ForeColor = Color.FromArgb(80, 160, 255);
            FLogin frm = new FLogin();
            frm.ShowDialog();
            if (frm.IsLogin)
            {
                ApplicationCache.CurrentUser = new CurrentUserModel();
                ApplicationCache.CurrentUser.LoginName = frm.user.LoginName;
                ApplicationCache.CurrentUser.Password = frm.user.Password;
                ApplicationCache.CurrentUser.DisplayName = frm.user.DisplayName;
                ApplicationCache.CurrentUser.Permission = frm.user.Permission;
                //Menu_Load(ApplicationCache.CurrentUser.permission.ToString(),menuId);
                UIMessageTip.ShowOk("登录成功");
            }

            if (ApplicationCache.CurrentUser.Permission == 0)
            {
                labelUser.Text = "超级管理员(" + ApplicationCache.CurrentUser.DisplayName + ")";
                timer1.Start();
            }
            else if(ApplicationCache.CurrentUser.Permission == 1)
            {
                labelUser.Text = "管理员(" + ApplicationCache.CurrentUser.DisplayName + ")";
                timer1.Start();
            }
            else if (ApplicationCache.CurrentUser.Permission == 2)
                labelUser.Text = "普通用户(" + ApplicationCache.CurrentUser.DisplayName + ")";
            frm.Dispose();
            //BllBaseAndong bllBaseAndong = new BllBaseAndong();
        }
        #endregion

        private void timer1_Tick(object sender, EventArgs e)
        {
            InitPermission();
        }

        /// <summary>
        /// 退出软件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FrmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            //if (UIMessageDialog.ShowMessageDialog("确定要退出系统吗？", UILocalize.AskTitle, true, UIStyle.Red, true, Frame?.TopMost ?? false))
            //{
            //    ShowWaitForm("正在关闭系统，请稍候...");
            //    foreach (UIPage page in UIPageList)
            //    {
            //        page.Close();
            //    }
            //    System.Environment.Exit(0);
            //    HideWaitForm();
            //}
            //else
            //{
            //    e.Cancel = true;
            //}
        }

        private void btnMin_Click(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Minimized;
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            if (UIMessageDialog.ShowMessageDialog("确定要退出系统吗？", UILocalize.AskTitle, true, UIStyle.Red, true, false))
            {
                this.timer1.Stop();
                System.Environment.Exit(0);
                this.Close();
            }
        }
    }
}
